package com.kevms.phonewars;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

/** 
* @class Menu
* 
* @brief Activity used to display all available menu options.
* 
* This Activity displays an array of buttons from which the
* user is allowed to pick from.
*/ 
public class Menu extends Activity {

	Context mContext;
	
	private SQLiteDatabase db;
	private MySQLiteHelper dbHelper;
	private Bitmap myBitmap = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu);
		mContext = this;
		
		setColor();
		loadProfilePic();
		
		Button btnEditProfile = (Button)findViewById(R.id.btnEditProfile);
		Button btnJoinMatch = (Button)findViewById(R.id.btnJoinMatch);
		Button btnCreateMatch = (Button)findViewById(R.id.btnCreateMatch);
		Button btnLogout = (Button)findViewById(R.id.btnLogout);
		
		Uri data = getIntent().getData();
		//String identity = data.getQueryParameter("openid.identity");
		String sessionid = data.getQueryParameter("sessionid");
		
		WebService webService = WebService.getInstance(this);
		webService.setSessionID(sessionid);
		
		btnCreateMatch.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent profileIntent = new Intent(mContext, CreateMatchType.class);
				startActivity(profileIntent);
			}
		});
		
		btnJoinMatch.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent profileIntent = new Intent(mContext, JoinMatchList.class);
				startActivity(profileIntent);
			}
		});
		
		btnEditProfile.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent profileIntent = new Intent(mContext, Profile.class);
				startActivityForResult(profileIntent, 0);
			}
		});
		
		btnLogout.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				WebService webService = WebService.getInstance(mContext);
				try {
					webService.logout();
				} catch (Exception e) {
					e.printStackTrace();
				}
				Menu.this.finish();
			}
		});
	}
	
	@Override
	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to logout?")
			.setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					Menu.this.finish();
				}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	private void setColor() {
		dbHelper = MySQLiteHelper.getInstance(getApplicationContext());
		db = dbHelper.getWritableDatabase();
		
		// For debugging purposes
		//dbHelper.onUpgrade(db,1,1);
		
		LinearLayout l = (LinearLayout)findViewById(R.id.topLayout);
    	l.setBackgroundColor(dbHelper.getBgColor(db));
	}
	
	public void loadProfilePic() {
		String path = dbHelper.getPicPath(db);
		if(path == null)
			return;
		File imgFile = new  File(path);
		if(imgFile.exists()) {
			if(myBitmap != null) {
				myBitmap.recycle();
				System.gc();
			}
			
			//myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
			myBitmap = decodeFile(imgFile);
		    ImageView ivPic = (ImageView)findViewById(R.id.ivPicky);
		    ivPic.setImageBitmap(myBitmap);
		}
	}
	
	//decodes image and scales it to reduce memory consumption
	private Bitmap decodeFile(File f){
	    try {
	        //Decode image size
	        BitmapFactory.Options o = new BitmapFactory.Options();
	        o.inJustDecodeBounds = true;
	        BitmapFactory.decodeStream(new FileInputStream(f),null,o);

	        //The new size we want to scale to
	        final int REQUIRED_SIZE=140;

	        //Find the correct scale value. It should be the power of 2.
	        int scale=1;
	        while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
	            scale*=2;

	        //Decode with inSampleSize
	        BitmapFactory.Options o2 = new BitmapFactory.Options();
	        o2.inSampleSize=scale;
	        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
	    } catch (FileNotFoundException e) {}
	    return null;
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		setColor();
		loadProfilePic();
    }
}
